<template>
  <el-dialog :title="dialogTitle" :visible="dialogShow" @close="handleClose" class="dia-box">
    <el-form :rules="rules" :model="form" label-width="80px" ref="formRef">

      <el-form-item label="角色名称" prop="name" >
        <el-input v-model="form.name"  />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="form.description" type="textarea"  :autosize="{ minRows: 4, }"/>
      </el-form-item>
   
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import {
  roleEdit,
  roleAdd
} from "@/api/role";
export default {
  name: "edit-role",
  props: {
    dialogShow: {
      type: Boolean,
      required: true
    },
    data: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      form: {
        role_id: "",
        name: "",
        description: ""
      },
      rules: {
      //  description: [
      //     { required: true, message: "请输入角色描述", trigger: "blur" },
      //     { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" }
      //   ],
        name: [
          { required: true, message: "评委名称不能为空", trigger: "blur" },
          { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" }
        ],
      
      },
    };
  },
  computed: {
    dialogTitle() {
      return this.data.role_id ? "编辑" : "新增角色";
    }
  },
  watch: {
    data: {
      handler(newData) {
        if (newData) {
          this.form = {
            ...this.data,
            role_id:this.data.role_id
          };
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    handleClose() {
      this.$emit("update:dialogShow", false);
      this.resetForm();
    },
    handleSubmit() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          if (this.data.role_id) {
            roleEdit(this.form).then(res => {
              this.$emit("update:dialogShow", false);
              this.$message.success("编辑成功");
              this.$emit("onUpdate");
              this.resetForm();
            });
          } else {
             roleAdd(this.form).then(res => {
              this.$emit("update:dialogShow", false);
              this.$message.success("新增成功");
              this.$emit("onUpdate");
              this.resetForm();
            });
          }
        } else {
          console.log("验证失败");
        }
      });
    },
    resetForm() {
      this.$refs.formRef.resetFields();
      this.form = {
        role_id: "",
        name: "",
        description: ""
      };
    }
  }
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}

.dia-box  ::v-deep .el-dialog{
  width: 520px;
  border-radius: 14px;
}
</style>